<script setup lang="ts">
import { ref } from 'vue'
import Default from './components/Default.vue'
import Result from './components/Result.vue';
import Suggest from './components/Suggest.vue';
import { getSuggest,getResult } from '../../services';
import type {SearchResSuggest,SearchResResult} from '../../services'

const suggestList = ref<SearchResSuggest[]>([])
let timer:number
const searchValue = ref()
const resultList = ref<SearchResResult[]>([])
const loading = ref(false)


enum showType {
    SUGGEST = 'SUGGEST',
    DEFAULT = 'DEFAULT',
    RESULT = 'RESULT'
}
const currentType = ref(showType.DEFAULT)


const getSuggestList = async (val:string) => {
    const res = await getSuggest(val)
    suggestList.value = res.result.allMatch
}



const search = async ({value}:{value:string})=>{
    loading.value = true
    currentType.value = showType.RESULT
    const res = await getResult(value)
    console.log(res)
    resultList.value = res.result.songs
    loading.value = false
}
const input = (val:string) => {
    if(val !== '' && !loading.value) {
        if(timer) clearTimeout(timer) 
        timer = setTimeout(() => {
            currentType.value = showType.SUGGEST
            getSuggestList(val)
        },500)
    }

}
const cancel = () => {
    currentType.value = showType.DEFAULT
}

const startSearch = (value:string) => {
    searchValue.value = value
    search({value})
}

</script>

<template>
    <uni-search-bar
    v-model="searchValue" 
    placeholder="搜索歌手/歌曲" 
    @confirm="search"
    @input="input"
    @cancel="cancel" 
    >
    </uni-search-bar>
    <Default v-if="currentType === showType.DEFAULT" @confirm="startSearch"/>
    <Suggest v-else-if="currentType === showType.SUGGEST" :list="suggestList" @confirm="startSearch"/>
    <Result v-else-if="currentType === showType.RESULT" :songs="resultList"/>
</template>

<style lang="scss" scoped>

</style>